#include <iostream>
#include <string>
using namespace std;
string remove_pattern1(string sentence, char c, int start, int end){
string result;
for(int i=0; i<start-1; ++i){
result=result+sentence[i];
}
if(start!=1 && sentence[start-2]!=' ') result+=' ';
for(int i=start-1; i<=end+1; i+=2){
result=result+sentence[i];
}
if(end+2!=sentence.length()) result+=' ';
for(int i=end+2; i<sentence.length(); ++i){
result=result+sentence[i];
}
return result;
}
string remove_pattern2(string sentence, char c, int start, int end){
string result;
for(int i=0; i<start; ++i){
result=result+sentence[i];
}
if(start!=0 && sentence[start-1]!=' ') result+=' ';
for(int i=start+1; i<end; ++i){
result=result+sentence[i];
}
if(end!=sentence.length()-1) result+=' ';
for(int i=end+1; i<sentence.length(); ++i){
result=result+sentence[i];
}
return result;
}
string solution(string sentence){
int size=sentence.length();
char c;
int rep, loc;
for(int i=0; i<size; ++i){
if(islower(sentence[i]))
c=sentence[i];
rep=0;
for(int j=i+1; j<size; ++j){
if(islower(sentence[j]) && sentence[j]==c){
rep++;
loc=j;
}
}
if(rep==1){
sentence=remove_pattern2(sentence, c, i, loc);
}else if(rep>1){
if(i==0 || sentence[i-1]==' '){
sentence="invalid";
return sentence;
}
sentence=remove_pattern1(sentence, c, i, loc);
}
}
return sentence;
}
int main(void){
string sentence1="HaEaLaLaObWORLDb";
string sentence2="SpIpGpOpNpGJqOqA";
string sentence3="AxAxAxAoBoBoB";
string answer1=solution(sentence1);
string answer2=solution(sentence2);
string answer3=solution(sentence3);
cout<<"Answer1: "<<answer1<<'\n';
cout<<"Answer2: "<<answer2<<'\n';
cout<<"Answer3: "<<answer3<<endl;
return 0;
}